package com.ltu.util.http;

import com.alibaba.fastjson.JSONObject;
import com.ltu.util.exception.ApiException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.Map;
public class HttpPostUtil {


	/**
	 * @Description:  向指定地址发送post请求，传入map参数
	 * @author: 若尘
	 * @date 2018年9月14日 下午4:00:34
	 * @version V1.0
	 */
	public  static  String  sendPost(String urlStr, Map<String, String> paramMap){
		String  result="";
		PrintWriter  out=null;
		BufferedReader   in=null;
		try {
			//创建一个远程请求对象
			URL  url=new URL (urlStr);
			//打开连接
			URLConnection conn=url.openConnection();
			//设置连接属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Charset", "UTF-8");
			 // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());
            // 设置请求属性  .
            String param = "";
            if (paramMap != null && paramMap.size() > 0) {
                Iterator<String> ite = paramMap.keySet().iterator();
                while (ite.hasNext()) {
                    String key = ite.next();// key  
                    String value = paramMap.get(key);
                    param += key + "=" + value + "&";
                }
                param = param.substring(0, param.length() - 1);
            }
            // 发送请求参数  
           System.out.println("最终传递的字符串"+param);
           out.print(param);
            // flush输出流的缓冲  
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
		} catch (MalformedURLException e) {
			  System.err.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		} catch (IOException e) {
			  System.err.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}catch (Exception e) {
            System.err.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

		return  result;
	}




	/**
     * 向指定URL发送POST请求
     * @param url
     * @param paramMap
     * @return 响应结果
     */
	public  static  String  sendPost(String urlStr, String param){
		String  result="";
		PrintWriter  out=null;
		BufferedReader   in=null;
		try {
			//创建一个远程请求对象
			URL  url=new URL (urlStr);
			//打开连接
			URLConnection conn=url.openConnection();
			//设置连接属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			//conn.setRequestProperty("Charset", "UTF-8");
			 // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());
            // 设置请求属性  .
            System.out.println("最终传递的字符串"+param);
            // 发送请求参数  
            out.print(param);
            // flush输出流的缓冲  
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
		} catch (MalformedURLException e) {
			  System.err.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		} catch (IOException e) {
			  System.err.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}catch (Exception e) {
            System.err.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
		return  result;
	}
	 /**
     * 数据流post请求
     * @param urlStr
     * @param xmlInfo
     */
    public static String doPost(String urlStr, String strInfo) {
        String reStr="";
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
            con.setRequestProperty("Charset", "UTF-8");
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write(new String(strInfo.getBytes("utf-8")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
                reStr += line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reStr;
    }

    /**
     * @date 2019年2月27日
     * @author 若尘
     * @Description  Content-Type = application/x-www-form-urlencoded  
     * 携带PKCS12证书( 是从微信商户平台-》账户设置-》 API安全 中下载的)的请求方法
     * @param url
     * @param data
     * @return 
     * @throws Exception
     * String
     */
    public static String sendPost_PKCS12(String url,String data,String mchid,String sslFilePath) throws Exception {

        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(sslFilePath));//P12文件在服务器磁盘中的目录
        try {
            keyStore.load(instream, mchid.toCharArray());//这里写密码..默认是你的MCHID
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, mchid.toCharArray())//这里也是写密码的
                .build();
        // Allow TLSv1 protocol only
        
//        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null,   SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
            HttpPost httpost = new HttpPost(url); // 设置响应头信息
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("UserEntity-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();

                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
               return jsonStr;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
    

    /**
     * @date 2019年2月27日
     * @author 若尘
     * @Description  Content-Type = 
     * 携带PKCS12证书( 是从微信商户平台-》账户设置-》 API安全 中下载的)的请求方法
     * @param url
     * @param data
     * @return 
     * @throws Exception
     * String
     */
    public static String sendPostRaw(String url,String data,String authorization,CloseableHttpClient httpclient) throws Exception {
    	
    	try {
    		HttpPost httpost = new HttpPost(url); // 设置响应头信息
    		httpost.addHeader("Authorization", authorization);
    		httpost.addHeader("Accept", "application/json");
    		httpost.addHeader("Content-Type", "application/json");
    		httpost.addHeader("Host", "api.mch.weixin.qq.com");
    		httpost.addHeader("UserEntity-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
    		httpost.setEntity(new StringEntity(data, "UTF-8"));
    		CloseableHttpResponse response = httpclient.execute(httpost);
    		try {
    			HttpEntity entity = response.getEntity();
    			
    			String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
    			EntityUtils.consume(entity);
    			return jsonStr;
    		} finally {
    			response.close();
    		}
    	} finally {
    		httpclient.close();
    	}
    }

    /**
     *
     * @param url 访问的链接
     * @param params 传入的参数，map转了的字符串
     * @return
     */

    public static String sendRawPost(String url,String params,String authorization)
    {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        try {
            httpClient = HttpClients.createDefault();

            httpPost = new HttpPost(url);

//            JSONObject json = new JSONObject();
//            json.put("areaName", "上海");
//            json.put("parentId", 0);
//            json.put("remark")

            StringEntity stringEntity = new StringEntity(params,"UTF-8");
//            stringEntity.setContentEncoding( "UTF-8" );
            stringEntity.setContentType( "application/json");
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
            httpPost.addHeader("Authorization", authorization);
            httpPost.addHeader("Accept", "application/json");
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
//            JSONObject resultJson=JSONObject.parseObject(jsonStr);
//            
//            if (!resultJson.getString("code").equals("00000000"))
//            {
//                throw new ApiException(resultJson.getString("message"));
//            }
            return jsonStr;

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(httpPost!=null){
                    httpPost.releaseConnection();
                }
                if(httpClient!=null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


}
